package com.hui.server.controller;

import com.hui.server.entity.Admin;
import com.hui.server.entity.AdminLogin;
import com.hui.server.service.AdminService;
import com.hui.server.service.RoleService;
import com.hui.server.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.controller
 * @Author: HUI
 * @CreateTime: 2022-04-03 12:45
 * @Description: 登录退出 Controller
 */

@Api(tags = "LoginController")
@RestController
@Slf4j
public class LoginController {

    private AdminService adminService;
    private RoleService roleService;


    @Autowired
    public LoginController(AdminService adminService, RoleService roleService) {
        this.adminService = adminService;
        this.roleService = roleService;
    }

    @ApiOperation("登录之后返回 token")
    @PostMapping("/login")
    public Result<?> login(@RequestBody AdminLogin adminLogin, HttpServletRequest request) {
        log.info("登录信息=" + adminLogin);
        return adminService.login(adminLogin.getUsername(), adminLogin.getPassword(), adminLogin.getCode(), request);
    }


    @ApiOperation("退出登录")
    @GetMapping("/user/logout")
    public Result<?> logout() {
        return Result.success("注销成功！");
    }


    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Authentication authentication) {
        if (authentication == null) {
            return null;
        }
        String username = authentication.getName();
        Admin admin = adminService.getAdminByUserName(username);
        log.info("获取用户信息的用户名：{}", admin.getName());
        admin.setPassword(null);

        //设置权限
        admin.setRoles(roleService.getRolesByAdminId(admin.getId()));
        return admin;
    }

}
